import Vue from 'vue'
import VueRouter from 'vue-router'
// 目标1: 通过路由实现登录注册组件的切换
// 1.1 创建两个组件: views/Login/Login.vue   views/Reg/Reg.vue
// 1.2 在 router/index.js 中进行路由配置
// 1.3 在 App.vue 中使用 router-view 组件占位

// 在 js 代码中写的 @ 符号都会被解析成 src 的绝对路径
import Login from '@/views/Login/Login.vue'
import Reg from '@/views/Reg/Reg.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'

import Home from '@/views/Menu/Home/Home.vue'
import UserInfo from '@/views/Menu/User/UserInfo.vue'
import UserAvatar from '@/views/Menu/User/UserAvatar.vue'
import UserPwd from '@/views/Menu/User/UserPwd.vue'
import ArtCate from '@/views/Menu/Article/ArtCate.vue'
import ArList from '@/views/Menu/Article/ArList.vue'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  // 一个对象表示一条路由规则
  { path: '/login', name: 'Login', component: Login },
  { path: '/reg', name: 'Reg', component: Reg },
  {
    path: '/',
    name: 'Main',
    component: Main,
    redirect: '/home', // redirect 要写完整的 path, 表示访问 / 时自动重定向到 /home
    children: [
      {
        path: 'home',
        name: 'Home',
        component: Home
      },
      {
        path: 'user-info',
        name: 'UserInfo',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        name: 'UserAvatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        name: 'UserPwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        name: 'ArtCate',
        component: ArtCate
      },
      {
        path: 'art-list',
        name: 'ArList',
        component: ArList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由的全局前置导航守卫: 路由切换之前进行拦截
// 参数1: 到哪里去
// 参数2: 从哪里来
// 参数3: 是否放行, 直接调用表示放行, 调用传入 false 表示拦截不放行, 调用传入 path 表示强制导航到指定路径
router.beforeEach((to, from, next) => {
  const whiteList = ['/login', '/reg']
  if (!whiteList.includes(to.path) && !store.state.token) {
    Vue.prototype.$message.error('看啥啊登录一下子啊!')
    // next() 函数一旦执行就不会执行下一个 next 函数了
    next('/login')
  }
  next()
})

export default router
